package com.jplus.core.plugin.aspect;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Expression {
	private final String SPACE = " ";
	private final String LP = "(";
	private final String RP = ")";
	private final String LINE = ".";
	private final String SPLIT = ",";

	private String expression;

	/**
	 * 1 通过方法类
	 */
	public Expression(Method method) {
		Class<?> declarClazz = method.getDeclaringClass();
		Class<?> returnClazz = method.getReturnType();
		Class<?> paramsClazz[] = method.getParameterTypes();
		String returnType = returnClazz.getSimpleName();// 包名有.的问题，待解决；所以使用短名称
		String classType = declarClazz.getName();
		String methodName = method.getName();
		List<String> paramsType = new ArrayList<>();
		if (paramsClazz.length > 0)
			for (Class<?> param : paramsClazz)
				paramsType.add(param.getSimpleName());// 短名称
		this.expression = build(returnType, classType, methodName, paramsType);
	}
	/**
	 * 1 通过regex
	 */
	public Expression(String regex) {
		regex = regex.replace(" ", "\\s");// \s 代表一个空格
		regex = regex.replace("*", "\\w*");// “*”表示任意类型的参数,不包含特殊字符
		regex = regex.replace("..", "\\S*");// “..”表示任意类型参数且参数个数不限，包含特殊字符
		regex = regex.replace("(\\S*)", "\\(\\S*\\)");
		this.expression = regex;
	}

	public String getExpression() {
		return expression;
	}
	public String build(String returnType, String classType, String methodName, List<String> paramsType) {
		StringBuilder sb = new StringBuilder(64);
		sb.append(returnType).append(SPACE).append(classType).append(LINE).append(methodName);
		sb.append(LP);
		if (paramsType.size() > 0) {
			for (int i = 0; i < paramsType.size(); i++) {
				sb.append(paramsType.get(i));
				if (i < paramsType.size() - 1)
					sb.append(SPLIT);
			}
		}
		sb.append(RP);
		return sb.toString();
	}
}